
/***
 *  @author:dingshihao 
 *  @email: dingshihao@victorysoft.com.cn
 *  @date：20191024
 *  @version:V1.1.0
 *  @description:
 *  此文档由崔良编写
 *  该模块开放函数在需要的地方引入即可，禁止全局引入，因为全局引入后您仍需要在每个使用的模块中单独引入
 *  该模块为处理ElementUI中Cascader 级联选择器控件v-model属性为所选项路径数组，
 *  1：cascaderTree([],string,string) 类构造器，用于构造一次转换,传入要转换的数组，数据主键名，父数据主键名
 *  2：cascaderTree.prototype.init(); 实例函数，用户将数据按配置初始化，形成树状结构的数据，并存在
 * 
 *  @example:
 *  let data = new cascaderTree(resp.data,"topicId","topicPid").init();
 * 
 *  @interface:
 *  cascaderTree.prototype.init()
 *  
 *  
 * 
 * 
 */ 


export default class cascaderTree{
  constructor (a, idKey, pIdKey){
    this.tree = a || [];
    this.idKey = idKey || "id";
    this.pIdKey = pIdKey || "pId";
    this.groups = {};
    this.ids = {};
    this.rootIds = [];
  }
  init() {
    this.group();
    let result = [];
    for (let i = 0; i < this.rootIds.length; i++) {
      let item = this.rootIds[i];
      let children = this.getChilds(this.groups[this.rootIds[i][this.idKey]]);
      if (children !== undefined && children.length > 0) {
        item.children = children;
      }
      result.push(item);
    }
    return result;
  }
  group() {
    for (let i = 0; i < this.tree.length; i++) {
      delete this.tree[i].children;// 删除多余children(空值)
      if (this.groups[this.tree[i][this.pIdKey]] === undefined) {
        this.groups[this.tree[i][this.pIdKey]] = [];
      }
      this.groups[this.tree[i][this.pIdKey]].push(this.tree[i]);
      if (this.ids[this.tree[i][this.idKey]] === undefined) {
        this.ids[this.tree[i][this.idKey]] = this.tree[i];
      }
    }
    for (let i = 0; i < this.tree.length; i++) {
      if (this.ids[this.tree[i][this.pIdKey]] === undefined) {
        this.rootIds.push(this.tree[i]);
        
      }
    }
  }
  getChilds(a) {
    if (!a) {
      return undefined;
    }
    let list = [];
    for (let i = 0; i < a.length; i++) {
      let o = a[i];
      let children = this.getChilds(this.groups[a[i][this.idKey]]);
      if (children && children.length > 0) {
        o.children = children;
      }
      list.push(o);
    }
    return list;
  }
}